﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace DaFunction
{
    internal class RSA
    {
        public static int Test()
        {
            return System.Threading.Thread.CurrentThread.ManagedThreadId;
        }

        public const int MAXDECRYPTSIZE = 128;
        /// <summary>   
        /// RSA解密   
        /// </summary>   
        /// <param name="encryptData">经过Base64编码的密文</param>   
        /// <param name="privateKey">私钥</param>   
        /// <returns>RSA解密后的数据</returns>   
        public static string Decrypt(string encryptData, string privateKey)
        {
            string decryptData = "";
            try
            {
                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                provider.FromXmlString(privateKey);
                byte[] bEncrypt = Convert.FromBase64String(encryptData);
                int length = bEncrypt.Length;
                int offset = 0;
                string cache;
                int i = 0;
                while (length - offset > 0)
                {
                    if (length - offset > MAXDECRYPTSIZE)
                    {
                        cache = Encoding.UTF8.GetString(provider.Decrypt(getSplit(bEncrypt, offset, MAXDECRYPTSIZE), false));
                    }
                    else
                    {
                        cache = Encoding.UTF8.GetString(provider.Decrypt(getSplit(bEncrypt, offset, length - offset), false));
                    }
                    decryptData += cache;
                    i++;
                    offset = i * MAXDECRYPTSIZE;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return decryptData;
        }

        /// <summary>   
        /// 截取字节数组部分字节   
        /// </summary>   
        /// <param name="input"></param>   
        /// <param name="offset">起始偏移位</param>   
        /// <param name="length">截取长度</param>   
        /// <returns></returns>   
        private static byte[] getSplit(byte[] input, int offset, int length)
        {
            byte[] output = new byte[length];
            for (int i = offset; i < offset + length; i++)
            {
                output[i - offset] = input[i];
            }
            return output;
        }
    }
}
